package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-admin/cache"
	"post-admin/model"
	"post-admin/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var user model.User
	redis_key := "login_" + username
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if CacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，两个小时之后再登录",
		})
		return
	}
	err := model.DB.Where("username =?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if CacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误次数过多，禁封两个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func ListPost(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var list []model.Post
	redis_key := "list_" + strconv.Itoa(page)
	CacheDate, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheDate == "" {
		model.DB.Offset(offset).Limit(size).Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheDate), &list)
	}
	var total int64
	model.DB.Model(&model.Post{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取成功",
		"data":  list,
		"total": total,
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var post model.Post
	err := model.DB.Where("id =?", id).Find(&post).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取详情失败",
		})
		return
	}
	redis_key := "post_detail_" + id
	jsonData, _ := json.Marshal(post)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": post,
	})
	return
}
